package exam2006.question3;

import java.io.IOException;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.Translator;

public class SingletonTranslator implements Translator {

	private CtClass c = null;

	@Override
	public void onLoad(ClassPool arg0, String arg1) throws NotFoundException,
			CannotCompileException {
		c = arg0.getCtClass(arg1);

	}

	@Override
	public void start(ClassPool arg0) throws NotFoundException,
			CannotCompileException {

		CtConstructor cons = c.getDeclaredConstructors()[0];
		if (cons.getParameterTypes().length != 0) {
			System.out.println("Constructor with arguments");
			return;
		}

		CtField field = CtField.make("private static " + c.getName()
				+ " singleInstance;", c);
		System.out.println("field added");
		c.addField(field);

		String body = "";
		body += "\tif(singleInstance!=null)";
		body += "\t\tsingleInstance= new " + c.getName() + "();";
		body += "\telse";
		body += "\t\tthrow new exam2006.question3.SingletonInstantiationException(\"already instanciate\");";

		cons.setBody(body);

		CtMethod getSingleInstance = CtMethod.make("public static "
				+ c.getName()
				+ " getSingleInstance(){ return singleInstance; }", c);
		c.addMethod(getSingleInstance);

		try {
			c.writeFile("bin");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
